﻿using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Linq;
using System;

namespace CodeMatrix.Utilities
{
    public class UiHelper
    {

        /// <summary>
        /// To get random data from collection
        /// </summary>
        /// <typeparam name="T">Desire type to manipulate</typeparam>
        /// <param name="cData">Collection to manipulate</param>
        /// <returns></returns>
        public static T GetRandomValue<T>(IEnumerable<T> cData)
        {
            int count = cData.Count();
            int targetValue = new Random(DateTime.Now.Millisecond).Next(0, count);
            T t = cData.ElementAt(targetValue);
            return t;
        }

        public static string[] GetSelectedCheckbox(GridView grv, string chkName, params string[] keyName)
        {

            List<string> items = new List<string>();
            foreach (GridViewRow i in grv.Rows)
            {

                if (i.RowType == DataControlRowType.DataRow)
                {
                    CheckBox iChk = i.FindControl(chkName) as CheckBox;
                    if (iChk.Checked)
                    {
                        String iStr = string.Empty;
                        foreach (string j in keyName)
                        {
                            iStr += "," + grv.DataKeys[i.RowIndex][j];
                        }
                        iStr = iStr.Remove(0, 1);
                        items.Add(iStr);
                    }
                }

            }
            return items.ToArray();
        }

        public static T[] GetSelectedCheckbox<T>(GridView grv, string chkName, string keyName)
        {

            List<T> items = new List<T>();
            foreach (GridViewRow i in grv.Rows)
            {

                if (i.RowType == DataControlRowType.DataRow)
                {
                    CheckBox iChk = i.FindControl(chkName) as CheckBox;
                    if (iChk.Checked)
                    {
                        items.Add((T)grv.DataKeys[i.RowIndex][keyName]);
                    }
                }

            }
            return items.ToArray();
        }

        public static void SetControlForListItem(System.Web.UI.WebControls.ListControl ctrl, ListItemCollection cItem)
        {
            ctrl.DataTextField = "Text";
            ctrl.DataValueField = "Value";
            ctrl.DataSource = cItem;
            ctrl.DataBind();

        }

    }
}

